/*
 * @Author: xiawei 1243162387@qq.com
 * @Date: 2024-04-19 11:14:35
 * @LastEditors: xiawei 1243162387@qq.com
 * @LastEditTime: 2024-05-17 15:26:22
 */
import express from 'express';
import fs from 'fs';
import path from 'path'
import { fileURLToPath } from 'url';
import bodyParser from 'body-parser';
import { getTableList } from './data/index.js'
const app = express();
const port = 3000;
const filename = fileURLToPath(import.meta.url);
const dirname = path.dirname(filename);
const filePath = path.join(dirname, '/files/');
import multer  from 'multer';
// 使用body-parser中间件解析JSON类型的请求体
app.use(bodyParser.json())
app.use(express.static(path.join(dirname, 'uploads')));
// 设置存储配置
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads/') // 确保这个文件夹已经存在
    },
    filename: function (req, file, cb) {
        let ext = path.extname(file.originalname);
        cb(null, file.fieldname + '-' + Date.now() + ext)
    }
})
const upload = multer({ storage: storage });

app.post('/api/file/writeFile', (req, res) => {
    if (req.body) {
        const file = req.body;
        fs.writeFile(`${filePath}${file.name}`, file.data, (err) => {
            if (err) {
                res.status(500).send(err);
            } else {
                res.status(200).send({
                    code: 20000
                });
            }
        });
    } else {
        res.status(500).send('文件写入失败');
    }
});
app.get('/api/file/readFile', (req, res) => {
    const file = req.query
    if (file.file) {
        fs.readFile(`${filePath}${file.file}`, "utf8", (err, data) => {
            if (err) {
                res.status(500).send(err);
            } else {
                res.status(200).send({
                    code: 20000,
                    result: data
                });
            }
        });
    } else {
        res.status(500).send('文件读取失败');
    }
});
app.post('/api/table/list', (req, res) => {
    const query = req.query
    res.status(200).send({
        code: 20000,
        result: {
            data: getTableList(),
            total: 10000,
        },
    });

});

// 单文件上传
app.post('/api/upload', upload.single('file'), (req, res) => {
    const file = req.file;
    if (!file) {
        return res.status(400).send('No file uploaded.');
    }
    req.file.path = `/${req.file.path}`
    res.json({ success: true, message: '文件上传成功', file: req.file })
});
app.listen(port, () => {
    console.log(`模拟服务器启动在 http://localhost:${port}`);
});